<template>
  <div>
    <Card title="运营统计">
      <div class="operTime">
        <span>时间：</span>
        <DatePicker
          type="daterange"
          :options="optionTime"
          format="yyyy-MM-dd"
          @on-change="handleChange"
          :value="startTime"
          :editable="false"
          split-panels
          style="width: 300px"
        ></DatePicker>
        <label class="select-store">选择门店：</label>
        <Col class="select-store-item">
          <Select v-model="storeCode" @on-change="handleStoreChange" size="large" clearable>
            <Option
              v-for="item in storeTableData"
              :value="item.storeCode"
              :key="item.id"
              :label="item.storeName"
            ></Option>
          </Select>
        </Col>
        <Button type="primary" @click="query">查询</Button>
        <Button type="success" @click="orderExport">导出</Button>
      </div>
      <div class="tabsList">
        <Table
          class="table-all-width"
          :columns="columns1"
          :data="data1"
          :stripe="true"
          :border="true"
          :loading="Tableloading"
        ></Table>
      </div>
    </Card>
  </div>
</template>

<script>
import { Format } from "@/assets/util";
import storage from "@/libs/storage";
import {
  chainOrderOperateStatistics,
  chainOrderExportOperateStatisticsExcel as orderExport
} from "@/api/order";
import { chainQueryBindStoreList } from "@/api/loginMenu";
import { saveAs } from "file-saver";
export default {
  data() {
    return {
      Tableloading: false,
      dateValue: [],
      pageSize: 20,
      pageNum: 1,
      optionTime: {
        shortcuts: [
          {
            text: "今日",
            value() {
              const start = new Date();
              const end = new Date();

              start.setHours(0, 0, 0, 0);

              start.setTime(start.getTime());
              end.setTime(end.getTime());
              return [start, end];
            }
          },
          {
            text: "昨日",
            value() {
              const start = new Date();
              const end = new Date();

              start.setHours(0, 0, 0, 0);
              end.setHours(0, 0, 0, 0);

              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              end.setTime(end.getTime() - 0.001);
              return [start, end];
            }
          },
          {
            text: "本周",
            value() {
              const start = new Date();
              const end = new Date();

              start.setHours(0, 0, 0, 0);

              let weekDay = start.getDay();
              let distance = weekDay - 1;
              if (weekDay === 0) {
                distance = 6;
              }

              start.setTime(start.getTime() - 3600 * 1000 * 24 * distance);
              end.setTime(end.getTime());
              return [start, end];
            }
          },
          {
            text: "本月",
            value() {
              const start = new Date();
              const end = new Date();

              start.setHours(0, 0, 0, 0);

              let firstDayOfMonth = new Date(start.getFullYear(), start.getMonth(), 1);
              firstDayOfMonth.setTime(firstDayOfMonth.getTime());
              return [firstDayOfMonth, end];
            }
          },
          {
            text: "上月",
            value() {
              let nowData = new Date();
              let currentMonth = nowData.getMonth();
              let currentYear = nowData.getFullYear();
              let start = new Date(currentYear, currentMonth - 1, 1);
              let end = new Date(currentYear, currentMonth, 0);
              return [start, end];
            }
          }
        ]
      },
      startTime: [],
      columns1: [
        {
          title: "序号",
          type: "index",
          width: 60,
          minWidth: 60,
          align: "center",
          className: "td-index"
        },
        {
          title: "门店编号",
          key: "storeCode",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "门店名称",
          key: "storeName",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "日期",
          key: "date",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "交易笔数",
          key: "tradeCount",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "欠款金额",
          key: "arrearsMoney",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "退货金额",
          key: "returnMoney",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "免单金额",
          key: "freeMoney",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "赠送金额",
          key: "giveMoney",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "优惠金额",
          key: "preferentialMoney",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "折扣金额",
          key: "rebateMoney",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "应收单均",
          key: "receivableOrderAverage",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "应收金额",
          key: "money",
          align: "center",
          headerAlign: "center"
        },
        {
          title: "实收金额",
          key: "realMoney",
          align: "center",
          headerAlign: "center"
        }
      ],
      data1: [],
      storeTableData: [], // 已绑定的门店数据
      storeCodeList: [], // 已选择的门店编号列表
      storeCode: "", // 与组件绑定的门店编号
      storeName: "" // 已选择的门店名称
    };
  },
  methods: {
    init() {
      let newTimeDate = new Date();
      this.startTime = [
        Format(newTimeDate, "yy-MM-dd"),
        Format(newTimeDate, "yy-MM-dd")
      ];
      this.dateValue = [
        Format(newTimeDate, "yy-MM-dd"),
        Format(newTimeDate, "yy-MM-dd")
      ];
      this.queryBranchStoreList();
    },
    daysBetween(sDate1, sDate2) {
      var dateSpan, iDays;
      sDate1 = Date.parse(sDate1);
      sDate2 = Date.parse(sDate2);
      dateSpan = sDate2 - sDate1;
      dateSpan = Math.abs(dateSpan);
      iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
      return iDays;
    },
    // 查询
    query() {
      let timeBet = this.daysBetween(this.dateValue[0], this.dateValue[1]);
      if (timeBet > 180) {
        this.$Message.error("最多查询半年内数据");
        return;
      }

      if (this.storeCodeList.length == 0) {
        this.$Message.error("请选择门店");
        return;
      }

      this.chainOrderOperateStatistics();
    },
    // 分页
    changePage(pageNum) {
      this.pageNum = pageNum;
      this.chainOrderOperateStatistics();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.pageNum = 1;
    },
    // 触发日历
    handleChange(daterange) {
      this.dateValue = daterange;
    },
    // 切换门店选择
    handleStoreChange(storeCode) {
      this.storeCodeList = [];

      // 选择全部门店
      if (storeCode == "0") {
        for (let index = 0; index < this.storeTableData.length; index++) {
          const storeInfo = this.storeTableData[index];
          if (storeInfo.storeCode != "0") {
            this.storeCodeList.push(storeInfo.storeCode);
            this.storeName = "全部门店";
          }
        }
        return;
      }

      // 添加选择的门店
      for (let index = 0; index < this.storeTableData.length; index++) {
        const storeInfo = this.storeTableData[index];
        if (storeCode == storeInfo.storeCode) {
          this.storeCodeList.push(storeCode);
          this.storeName = storeInfo.storeName;
          break;
        }
      }
    },
    // 已绑定门店列表
    async queryBranchStoreList() {
      const Loading = this.$myLoading({
        content: ""
      });
      const { data, status } = await chainQueryBindStoreList('');
      if (data.code == 200 && status == 200) {
        this.showModal = false;
        this.storeTableData = [{ storeCode: "0", storeName: "全部门店" }].concat(data.data);
        this.handleStoreChange(this.storeTableData[0].storeCode);
        this.storeCode = this.storeTableData[0].storeCode;
        this.query();
      } else {
        this.$Message.error(data.message);
      }
      Loading.close();
    },
    // 列表
    async chainOrderOperateStatistics() {
      const Loading = this.$myLoading({
        content: ""
      });
      this.Tableloading = true;
      const item = {
        beginTime: this.dateValue[0],
        endTime: this.dateValue[1],
        page: this.pageNum,
        pageSize: this.pageSize,
        storeList: this.storeCodeList
      };
      const { data } = await chainOrderOperateStatistics(item);
      if (data.code == 200) {
        this.total = data.data.total;
        this.data1 = data.data;
        setTimeout(() => {
          Loading.close();
          this.Tableloading = false;
        }, 1000);
      } else {
        Loading.close();
        this.Tableloading = false;
        this.$Message.error(data.message);
      }
    },
    async orderExport() {
      const item = {
        beginTime: this.dateValue[0],
        endTime: this.dateValue[1],
        storeCodeList: this.storeCodeList
      };
      const { data, status } = await orderExport(item);
      if (status == 200) {
        let newTimeDate = new Date();
        let date = Format(newTimeDate, "yy年MM月dd日hh时mm分ss秒");
        saveAs(data, this.storeName + "—营运统计报表—" + date + ".xls");
      }
    }
  },
  mounted: function() {
    this.init();
  }
};
</script>

<style scoped>
.operTime button {
  margin-left: 15px;
}
.select-store {
  text-align: right;
  line-height: 32px;
  height: 32px;
  width: 100px;
  font-size: 14px;
  margin-left: 30px;
}
.select-store-item {
  text-align: left;
  height: 32px;
  font-size: 14px;
  display: inline-block;
  width: 30%;
}
.tabsList {
  margin-top: 15px;
}
</style>
